﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Gammar.Digger.BLL;
using Gammar.Digger.Entity;
using Gammar.Digger.SystemFramework;
using System.Text;
using System.Xml;
using System.Collections.Generic;

public partial class plugin_Manage : System.Web.UI.Page
{
    private string pluginId = string.Empty;


    protected void Page_Load(object sender, EventArgs e)
    {
        //this.SmartNavigation = true;
        pluginId = Request.QueryString["pluginId"];
        lblmsg.Text = "";

        if (!string.IsNullOrEmpty(pluginId))
        {
            btnGeneric.Visible = false;
        }
        else
        {
            btnGeneric.Visible = true;
        }

        if (!IsPostBack)
        {
            BindData();
        }
       
    }
    protected void Bt_GatherAdd_Click(object sender, EventArgs e)
    {


        digger_pluginEntity plugin = new digger_pluginEntity();
        if (!string.IsNullOrEmpty(pluginId))//编辑状态
        {
            plugin = (digger_pluginEntity)ViewState["plugin"];
            
        }
        else
        {
            plugin.run_status = 0;
        }
        plugin.name = TB_GatherName.Text;
        
        plugin.start_url = TB_ListUrl.Text;
        plugin.list_area_rule = TB_ListArea.Text;
        plugin.list_url_rule=TB_ListURLRule.Text;
        plugin.list_nextPage_rule = TB_ListNextUrl.Text;
        
        plugin.content_url_rule = TB_PageUrl.Text;
        plugin.content_title_rule = TB_Title.Text;
        plugin.content_detail_rule = BuildContent();
        plugin.content_nextPage_rule = TB_PageNextUrl.Text;
        plugin.content_originalPrice_rule = TB_originalPrice.Text;
        plugin.content_salePrice_rule = TB_salePrice.Text;
        plugin.content_CreateDate_rule = TB_Date.Text;
       
        plugin.thread_number =int.Parse(txtPluginThreadNumber.Text);
        plugin.site_id =int.Parse(ddlWebSite.SelectedValue);
        plugin.max_number =int.Parse(TB_Num.Text);
        plugin.is_download_flash = DownFlash.SelectedValue == "1" ? true : false;
        plugin.is_download_image = DownImg.SelectedValue == "1" ? true : false;
        plugin.is_valid = isValid.SelectedValue == "1" ? true : false;
        plugin.dig_depth =int.Parse(TB_Depth.Text);
        plugin.page_Encode = ddlEncode.SelectedValue;

        DropDownList ddl = WebSiteCategoryDDL1.FindControl("DropDownList1") as DropDownList;
        plugin.category_id =new Guid(ddl.SelectedValue);

        string message = string.Empty;
        if (!string.IsNullOrEmpty(pluginId))
        {
            plugin.last_modify_time = StringHelper.DateTimeToLong(DateTime.Now);
             message = PluginManagement.Update(plugin);
             BindData();
        }
        else
        { 
            plugin.create_time = StringHelper.DateTimeToLong(DateTime.Now);
            plugin.last_modify_time = StringHelper.DateTimeToLong(DateTime.Now);
            message = PluginManagement.Add(plugin);
        }


        lblmsg.Text = message;
        
        

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(pluginId))
        {
            ;
        }
        else
        {
            GenerateTextBox(null);
        }
        
        //for (int i = 0; i < int.Parse(txtGenericNumber.Text); i++)
        //{
        //    TextBox tbx = new TextBox();
        //    tbx.ID = "Name_"+i.ToString();
        //    tbx.Width = Unit.Pixel(100);

        //    TextBox tbx1 = new TextBox();
        //    tbx1.ID = "Value_" + i.ToString();
        //    tbx1.Width = Unit.Pixel(300);
        //    if (i==0)
        //    {
        //        ph.Controls.Add(new LiteralControl("标签名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;规则<br>"));
        //    }
        //    ph.Controls.Add(tbx);
        //    ph.Controls.Add(tbx1);
        //    ph.Controls.Add(new LiteralControl("<br>"));
        //}
        //lblNumber.Text = txtGenericNumber.Text;
    }

    private string BuildContent()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        sb.Append("<root>");
        sb.Append("<content><![CDATA[");
        sb.Append(TB_Content.Text);
        sb.Append("]]></content>");

        Label lbl=this.FindControl("lblNumber") as Label;
        
        if (!string.IsNullOrEmpty(lbl.Text) && lbl.Text != "0")
        {
            int sum = int.Parse(lbl.Text);
            for (int i = 0; i < sum; i++)
            {
                string name = Request.Form["Name_"+i.ToString()];
                string value = Request.Form["Value_" + i.ToString()];

                sb.Append(string.Format("<{0}><![CDATA[", name));
                sb.Append(value);
                sb.Append(string.Format("]]></{0}>", name));
            }
        }
        sb.Append("</root>");

        return sb.ToString();
    }

    private void GenerateControlsByXML(string xmlsource)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlsource);

        XmlNode pnode = doc.SelectSingleNode("root");

        XmlNodeList list = pnode.ChildNodes;
        Label lbl = this.FindControl("lblNumber") as Label;

        lbl.Text = (list.Count - 1).ToString();
        txtGenericNumber.Text =(list.Count - 1).ToString();
        Dictionary<string, string> dic = new Dictionary<string, string>();
        foreach (XmlNode node in list)
        {
            if (node.Name=="content")
            {
                TB_Content.Text = node.InnerText;
            }
            else
            {
                dic.Add(node.Name, node.InnerText);
            }
        }

        GenerateTextBox(dic);
    }

    private void GenerateTextBox(Dictionary<string, string> dic)
    {
        for (int i = 0; i < int.Parse(txtGenericNumber.Text); i++)
        {

            TextBox tbx = new TextBox();
            tbx.ID = "Name_" + i.ToString();
            tbx.Width = Unit.Pixel(100);

            TextBox tbx1 = new TextBox();
            tbx1.ID = "Value_" + i.ToString();
            tbx1.Width = Unit.Pixel(300);

            if (dic!=null)
            {
                tbx.Text = dic.ElementAt(i).Key;
                tbx1.Text = dic.ElementAt(i).Value;
            }

            if (i == 0)
            {
                ph.Controls.Add(new LiteralControl("标签名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;规则<br>"));
            }

            if (!ph.Controls.Contains(tbx))
            {
                ph.Controls.Add(tbx);
            }

            if (!ph.Controls.Contains(tbx1))
            {
                ph.Controls.Add(tbx1); ph.Controls.Add(new LiteralControl("<br>"));
            }
            
           
        }
        lblNumber.Text = txtGenericNumber.Text;
    }

    private void BindData()
    {
        //bind website dropdowlist
        ddlWebSite.DataSource = WebSiteManagement.GetAllWebSite();
        ddlWebSite.DataTextField = "name";
        ddlWebSite.DataValueField = "site_id";
        ddlWebSite.DataBind();

        if (!string.IsNullOrEmpty(pluginId))
        {
            digger_pluginEntity plugin = PluginManagement.GetPluginById(pluginId);

            if (plugin==null)
            {
                Response.Write("无效插件号");
                Response.End();
            }

            ViewState["plugin"] = plugin;
            TB_GatherName.Text = plugin.name;
            TB_ListUrl.Text = plugin.start_url;
            TB_ListArea.Text = plugin.list_area_rule;
            TB_ListURLRule.Text = plugin.list_url_rule;

            TB_ListNextUrl.Text = plugin.list_nextPage_rule;

            TB_PageUrl.Text = plugin.content_url_rule;
            TB_Title.Text = plugin.content_title_rule;
            TB_Depth.Text = plugin.dig_depth.ToString();
          
            //为内容文本赋值，生成附属信息
            GenerateControlsByXML(plugin.content_detail_rule);

            TB_PageNextUrl.Text = plugin.content_nextPage_rule;
            TB_originalPrice.Text = plugin.content_originalPrice_rule;
            TB_salePrice.Text = plugin.content_salePrice_rule;
            TB_Date.Text = plugin.content_CreateDate_rule;
            txtPluginThreadNumber.Text = plugin.thread_number.ToString();
            if ((bool)plugin.is_valid)
            {
                isValid.Items.FindByValue("1").Selected = true;
            }
            else
            {
                isValid.Items.FindByValue("0").Selected = true;
            }
            //txtWebId.Text = plugin.site_id.ToString();

            SortList<web_siteEntity> weblist = WebSiteManagement.GetAllWebSite();

            foreach (web_siteEntity site in weblist)
            {
                if (site.site_id==plugin.site_id)
                {
                    ddlWebSite.Items.FindByValue(plugin.site_id.ToString()).Selected = true;
                }
            }

            if (plugin.category_id!=null)
            {
                WebSiteCategoryDDL1.BindKey = plugin.category_id.ToString();
            }

            if (!String.IsNullOrEmpty(plugin.page_Encode))
            {
                ddlEncode.Items.FindByValue(plugin.page_Encode).Selected = true;
            }
           
           
        }
    }
}
